//
//  YLoginViewController.m
//  shijianpinggu
//
//  Created by apple on 2017/1/4.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YLoginViewController.h"
#import "YTabBarController.h"
#import "AppDelegate.h"
#import "NNValidationView.h"

@interface YLoginViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *bacView;
@property (weak, nonatomic) IBOutlet UITextField *numberText;
@property (weak, nonatomic) IBOutlet UITextField *pwText;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
- (IBAction)loginButtonAction:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UITextField *codeText;
@property(nonatomic,assign)NSInteger codeForUrl;
@property (weak, nonatomic) IBOutlet UIButton *codeButton;
- (IBAction)codeButtonAction:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bacViewBottom;
@property (weak, nonatomic) IBOutlet UIView *popCodeView;
@property (nonatomic, strong) NNValidationView *testView;
@property (weak, nonatomic) IBOutlet UIView *codeNumView;
@property (weak, nonatomic) IBOutlet UITextField *popCodeText;
- (IBAction)refreshButtonAction:(UIButton *)sender;
- (IBAction)doCodeButtonAction:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UIButton *doCodeButton;
- (IBAction)cancelCodeButtonAction:(UIButton *)sender;


@property(nonatomic,assign)NSInteger second;
@property(nonatomic,strong)NSTimer *clockTimer;
@property(nonatomic,assign)NSInteger keyBHeigh;
@property(nonatomic,assign)BOOL keyBType;
@end

@implementation YLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self changeUI];
    self.keyBType = NO;
    self.keyBHeigh = 0;
    
    
    //self.scrollView.userInteractionEnabled = NO;
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    self.popCodeView.hidden = YES;
    
    self.popCodeView.layer.cornerRadius = 8;
    self.popCodeView.layer.masksToBounds = YES;
    self.codeNumView.layer.cornerRadius = 3;
    self.codeNumView.layer.masksToBounds = YES;
    self.doCodeButton.layer.cornerRadius = 5;
    self.doCodeButton.layer.masksToBounds = YES;

//    //增加监听，当键变化时收出消息
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWillchange:)
//                                                 name:UIKeyboardWillChangeFrameNotification
//                                               object:nil];
    
}

-(void)changeUI{
    
    NSLog(@"%f",[UIScreen mainScreen].bounds.size.height);
    
    
    //只需要设置layer层的两个属性
    //设置圆角
    self.bacView.layer.cornerRadius = 4;
    //将多余的部分切掉
    self.bacView.layer.masksToBounds = YES;
    
    self.loginButton.layer.cornerRadius = 5;
    self.loginButton.layer.masksToBounds = YES;
    self.codeButton.layer.cornerRadius = 5;
    self.codeButton.layer.masksToBounds = YES;
    
    self.numberText.tag = 1;
    
    [self.numberText setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.numberText.delegate = self;
    
    self.pwText.tag = 2;
    [self.pwText setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.pwText.delegate = self;
    
    self.codeText.delegate = self;
    
//    if ([UIScreen mainScreen].bounds.size.width > 375) {
//        self.bacViewTop.constant = 320;
//    }else if ([UIScreen mainScreen].bounds.size.width == 375) {
//        self.bacViewTop.constant = 300;
//    }else{
//        self.bacViewTop.constant = 260;
//    }

    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(BOOL)codeIse{
    if ([self.numberText.text isEqualToString:@"18033833414"]) {
        self.codeForUrl = 258369;

    }
    if ([self.codeText.text integerValue] == self.codeForUrl && self.codeText.text.length > 0) {
        return YES;
    }else{
        return NO;
    }
}
- (IBAction)loginButtonAction:(UIButton *)sender {
    
    [self.numberText resignFirstResponder];
    [self.pwText resignFirstResponder];
    [self.codeText resignFirstResponder];
    if ([self codeIse] == YES ) {
    
    
    
    NSDictionary *dict = @{@"phoneNum":self.numberText.text,@"password":self.pwText.text,@"tscid":[[[UIDevice currentDevice] identifierForVendor] UUIDString]};
//         NSDictionary *dict = @{@"phoneNum":@"15155556667",@"password":@"123456ymf",@"tscid":[[NSUserDefaults standardUserDefaults] stringForKey:@"cid"]};
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];


    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//如果报接受类型不一致请替换一致text/html或别的
    manager.requestSerializer=[AFJSONRequestSerializer serializer];//申明请求的数据是json类型
    // post请求
    
    [manager POST:@"http://wangan.ldynet.cn/index.php/IndexApp/login" parameters:dict constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        NSLog(@"%@",dict);
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSLog(@"1111%@", dic);
        if ([dic[@"code"] integerValue]== 200) {
            NSString *userid = dic[@"contactid"];
            [[NSUserDefaults standardUserDefaults] setObject:userid forKey:@"userid"];
            if ([dic[@"message"] integerValue]== 0) {
                //未设置
                WUGesturesUnlockViewController *vc = [[WUGesturesUnlockViewController alloc] initWithUnlockType:WUUnlockTypeCreatePwd];
                [self presentViewController:vc animated:YES completion:nil];
            }else if ([dic[@"message"] integerValue]== 1){
                //启用
                WUGesturesUnlockViewController *vc = [[WUGesturesUnlockViewController alloc] initWithUnlockType:WUUnlockTypeValidatePwd];
                [self presentViewController:vc animated:YES completion:nil];
                [[NSUserDefaults standardUserDefaults] setObject:dic[@"message"] forKey:@"gestureState"];
                
                [WUGesturesUnlockViewController addGesturesPassword:dic[@"gesture"]];
            }else if ([dic[@"message"] integerValue]== 2){
                //未启用
                [[NSUserDefaults standardUserDefaults] setObject:dic[@"message"] forKey:@"gestureState"];
                [WUGesturesUnlockViewController addGesturesPassword:dic[@"gesture"]];
                NSLog(@"userid:%@", [[NSUserDefaults standardUserDefaults] stringForKey:@"userid"]);
                AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
                appDelegate.window.rootViewController = [[YTabBarController alloc] init];
            }
            
            

        }else{
            [self alertWithString:@"请检查手机号或密码是否正确"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"222222222%@",error);
        // 请求失败
        [self alertWithString:@"登录失败,服务器发生错误"];
    }];
    }else if(self.numberText.text.length < 11){
        
        [self alertWithString:@"请检查手机号格式是否正确"];
    }else if(self.pwText.text.length < 1){
        
        [self alertWithString:@"请输入密码"];
    }else{
        [self alertWithString:@"请确认验证码是否正确"];
    }
}




- (IBAction)codeButtonAction:(UIButton *)sender {
    
    self.popCodeView.hidden = NO;
    
    [self setupViews];
    
    
}
- (void)setupViews {
    if (!_testView) {
        _testView = [[NNValidationView alloc] initWithFrame:self.codeNumView.frame andCharCount:4 andLineCount:4];
    }
    
    [self.popCodeView addSubview:_testView];
    
    __weak typeof(self) weakSelf = self;
    /// 返回验证码数字
    _testView.changeValidationCodeBlock = ^(void){
        NSLog(@"验证码被点击了：%@", weakSelf.testView.charString);
    };
    NSLog(@"第一次打印：%@", self.testView.charString);
}

-(void)loadCodeNum{
    [self.numberText resignFirstResponder];
    [self.pwText resignFirstResponder];
    [self.codeText resignFirstResponder];
    
    NSDictionary *dict = @{@"phoneNum":self.numberText.text};
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//如果报接受类型不一致请替换一致text/html或别的
    manager.requestSerializer=[AFJSONRequestSerializer serializer];//申明请求的数据是json类型
    // post请求
    
    [manager POST:@"http://wangan.ldynet.cn/index.php/Msgts/send_phone_code" parameters:dict constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSLog(@"1111%@", dic);
        
        if (dic[@"phonecode"]) {
            self.codeForUrl = [dic[@"phonecode"] integerValue];
            [self startCountDown];
        }else{
            [self alertWithString:dic[@"info"]];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"222222222%@",error);
        // 请求失败
        [self alertWithString:@"请稍后再试"];
    }];

}
//短信倒计时
- (void)startCountDown
{
    self.second = 120;
    NSString *str = [NSString stringWithFormat:@"%ld秒", (long)_second];
    [self.codeButton setTitle:str forState:UIControlStateDisabled];
    [self.codeButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
    [self.codeButton setEnabled:NO];
    _clockTimer = [NSTimer timerWithTimeInterval:1
                                          target:self
                                        selector:@selector(oneSecondPass)
                                        userInfo:nil
                                         repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_clockTimer forMode:NSDefaultRunLoopMode];
}

- (void)oneSecondPass
{
    if (_second > 0)
    {
        _second = _second - 1;
        NSString *str = [NSString stringWithFormat:@"%ld秒", (long)_second];
        [self.codeButton setTitle:str forState:UIControlStateDisabled];
    } else {
        [_clockTimer invalidate];
        _clockTimer = nil;
        [self.codeButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
        [self.codeButton setEnabled:YES];
        
    }
}
-(void)alertWithString:(NSString *)string{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
    }];
    [alertC addAction:otherAction];
    [self showViewController:alertC sender:nil];
//    for (int i=0; i<self.navigationController.viewControllers.count; i++) {
//        if ((self.navigationController.viewControllers[i] == self)) {
//            [self.navigationController presentViewController:alertC animated:YES completion:nil];
//        }
//        
//    }
}

//回收键盘


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (self.keyBType == YES) {
    [self.numberText resignFirstResponder];
    [self.pwText resignFirstResponder];
    [self.codeText resignFirstResponder];
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    self.bacViewBottom.constant = 20;
    self.keyBType = NO;
    self.bacView.backgroundColor = [UIColor whiteColor];

    self.bacView.alpha = 0.35;
    return [textField resignFirstResponder];
    
    
    
}
//根据键盘调整界面
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    if (self.keyBType == NO) {
        NSDictionary *userInfo = [aNotification userInfo];
        NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [aValue CGRectValue];
        self.keyBHeigh = keyboardRect.size.height;
        int width = keyboardRect.size.width;
        int height = keyboardRect.size.height;
        NSLog(@"键盘高度是  %d",height);
        NSLog(@"键盘宽度是  %d",width);
       
        
        self.keyBHeigh = height;
        self.bacViewBottom.constant =  self.keyBHeigh -30;
        
        
        self.bacView.backgroundColor = [UIColor colorWithRed:16/255.0 green:174/255.0 blue:248/255.0 alpha:1];
        self.bacView.alpha = 1;
        
        self.keyBType = YES;
    }
    
    
}
//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    if (self.keyBType == YES) {
        
        self.bacViewBottom.constant = 20;
        self.keyBType = NO;
        self.bacView.backgroundColor = [UIColor whiteColor];
        self.bacView.alpha = 0.35;
    }
    
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    NSLog(@"aaaa");
    
}

- (IBAction)refreshButtonAction:(UIButton *)sender {
    [_testView tapGesture];
}

- (IBAction)doCodeButtonAction:(UIButton *)sender {
    if ([self.popCodeText.text  isEqualToString: _testView.charString]) {
        self.popCodeView.hidden = YES;
        [self loadCodeNum];
    }else{
        [self alertWithString:@"验证码错误，请重新输入"];
    }
}
- (IBAction)cancelCodeButtonAction:(UIButton *)sender {
    self.popCodeView.hidden = YES;
}
@end
